<template>
  <div class="threejs-container">
    <div class="center" v-if="showProgress">
      <el-progress class="progress" type="circle"  :percentage="progressNum"></el-progress>
    </div>
  </div>
</template>

<script>
import ThreeBase from './three-base.js'

export default {
  props: {
    // 场景纹理url
    sceneUrl: {
      type: String,
      required: true
    },
    // 模型url
    modelUrl: {
      type: String
    },
    model: {
      type: String,
      default: ''
    },
    // 是否自动旋转
    autoRotate: {
      type: Boolean,
      default: true
    },
    // 生成的canvas是否铺满浏览器
    isFullBrowser: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showProgress: false,
      progressNum: 0,
      threeView: null
    }
  },
  watch: {
    sceneUrl(val) {
      this.threeView.loadScene(val)
    },
    modelUrl(val) {
      console.log('加载', val)
      this.threeView.loadModel(val)
    },
    autoRotate(val) {
      this.threeView.controlsRotate(val)
    }
  },
  beforeDestroy () {
			console.log('beforeDestroy===')
			if (this.threeView) {
				this.threeView.destroy()
				this.threeView = null
			}
		},
  methods: {
    reset() {
      if (this.threeView) {
					this.threeView.reset()
				}
    }
  },
  mounted() {
    this.threeView = new ThreeBase(
      this.$el,
      {
        sceneUrl: this.sceneUrl,
        modelUrl: this.modelUrl,
        autoRotate: this.autoRotate,
        model: this.model,
        isFullBrowser: this.isFullBrowser
      },
      (progressNum) => {
        if (!Number.isFinite(progressNum)) {
          progressNum = 0
        }
        this.showProgress = true
        this.$nextTick(() => {
          let num = parseInt(progressNum)
          if (num === 100) {
            setTimeout(() => {
              this.progressNum = 100
              setTimeout(() => {
                this.$emit('finished')
                this.showProgress = false
              }, 200)
            }, 300)
          } else {
            this.progressNum = num
          }
        })
      }
    )
  }
}
</script>

<style lang="scss">
.threejs-container {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: grab;
  overflow: hidden;
}
.center {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  left: 0px;
  right: 0px;
  bottom: 0px;
  top: 0px;
  z-index: 999;
}
.progress {
  background-color: #fff;
}
</style>
